import { defineStore } from 'pinia';
import { v4 as uuid } from 'uuid';
import eventBus, { Events } from '@/event-bus';
import type { Scene } from '@/types';
import { useBlocksStore } from './blocks';

// 本地存储键名
const LOCAL_STORAGE_KEY = 'vehicle_sim_scenes';

export const useSceneStore = defineStore('scene', {
    state: () => ({
        // 当前场景
        currentScene: null as Scene | null,
        // 场景列表
        scenes: [] as Scene[],
        // 是否正在保存
        isSaving: false,
        // 是否正在加载
        isLoading: false
    }),

    actions: {
        /**
         * 初始化场景存储（从本地存储加载）
         */
        init() {
            const savedScenes = localStorage.getItem(LOCAL_STORAGE_KEY);
            if (savedScenes) {
                try {
                    this.scenes = JSON.parse(savedScenes);
                } catch (e) {
                    console.error('Failed to load scenes from localStorage', e);
                    this.scenes = [];
                }
            }
        },

        /**
         * 创建新场景
         * @param name 场景名称
         * @param description 场景描述
         */
        createNewScene(name: string, description: string = '') {
            const newScene: Scene = {
                id: uuid(),
                name,
                description,
                blocks: [],
                createdAt: new Date(),
                updatedAt: new Date()
            };

            this.currentScene = newScene;
            this.scenes.push(newScene);

            // 清空当前块
            const blocksStore = useBlocksStore();
            blocksStore.clearAllBlocks();

            // 保存到本地存储
            this.saveScenesToLocalStorage();

            eventBus.emit(Events.SCENE_LOADED, newScene);
        },

        /**
         * 保存当前场景
         */
        saveCurrentScene() {
            if (!this.currentScene) return;

            this.isSaving = true;

            try {
                const blocksStore = useBlocksStore();

                // 更新当前场景的块和时间
                this.currentScene.blocks = [...blocksStore.blocks];
                this.currentScene.updatedAt = new Date();

                // 更新场景列表中的对应场景
                const index = this.scenes.findIndex(s => s.id === this.currentScene!.id);
                if (index !== -1) {
                    this.scenes[index] = this.currentScene;
                } else {
                    this.scenes.push(this.currentScene);
                }

                // 保存到本地存储
                this.saveScenesToLocalStorage();

                eventBus.emit(Events.SCENE_SAVED, this.currentScene);
            } catch (e) {
                console.error('Failed to save scene', e);
            } finally {
                this.isSaving = false;
            }
        },

        /**
         * 加载场景
         * @param sceneId 场景ID
         */
        loadScene(sceneId: string) {
            const scene = this.scenes.find(s => s.id === sceneId);
            if (!scene) return;

            this.isLoading = true;

            try {
                // 更新当前场景
                this.currentScene = {...scene};

                // 加载块
                const blocksStore = useBlocksStore();
                blocksStore.setBlocks(scene.blocks);

                eventBus.emit(Events.SCENE_LOADED, scene);
            } catch (e) {
                console.error('Failed to load scene', e);
            } finally {
                this.isLoading = false;
            }
        },

        /**
         * 删除场景
         * @param sceneId 场景ID
         */
        deleteScene(sceneId: string) {
            // 如果删除的是当前场景，重置当前场景
            if (this.currentScene && this.currentScene.id === sceneId) {
                this.currentScene = null;
                const blocksStore = useBlocksStore();
                blocksStore.clearAllBlocks();
            }

            // 从场景列表中删除
            this.scenes = this.scenes.filter(s => s.id !== sceneId);

            // 保存到本地存储
            this.saveScenesToLocalStorage();
        },
        /**
         * 将场景保存到本地存储
         */
         saveScenesToLocalStorage() {
            try {
                localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(this.scenes));
            } catch (e) {
                console.error('Failed to save scenes to localStorage', e);
            }
        }
    }
});
